// 云函数入口文件
const cloud = require('wx-server-sdk')
const { WXMINIUser } = require('wx-js-utils')
const axios = require('axios')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { userInfo, ...body } = event

  const {
    data: [{ appId, secret, env }],
  } = await db.collection('config').get()
  const wXMINIUser = new WXMINIUser({ appId, secret })
  const token = await wXMINIUser.getCacheAccessToken()

  let {
    data: { errcode, errmsg, resp_data: pData },
  } = await axios.post(
    'https://api.weixin.qq.com/tcb/invokecloudfunction',
    body,
    { params: { access_token: token, env, name: 'list-all-promotion' } }
  )
  if (errcode) {
    throw new Error(errmsg)
  }
  pData = JSON.parse(pData)

  return pData
}
